﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebWindow.GLKService;

namespace WebWindow.Controllers
{
    public class MainController : Controller
    {
        /// <summary>
        /// Шаг 0: Вход на сайт
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Шаг 1: Наш ли это клиент?
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult IsOurUser(bool id = false)
        {
            return View(id ? "Identification" : "Registration");
        }

        /// <summary>
        /// Шаг 2: Вариант 1: Идентификация
        /// </summary>
        /// <returns></returns>
        public ActionResult Identification()
        {
            var email = Request["email"];
            if (string.IsNullOrWhiteSpace(email)) { return Redirect("/Main/IsOurUser/True"); }
            var clientID = new GLKServiceClient().GetClientByEmail(email);
            if (clientID == 0) { return Redirect("/Main/IsOurUser/True"); }
            var cookie = FormsAuthentication.GetAuthCookie(clientID.ToString(), true);
            cookie.Expires = DateTime.Now.AddHours(2);
            Response.Cookies.Set(cookie);
            ViewBag.Action = "All";
            return View("Action");
        }

        /// <summary>
        /// Шаг 2: Вариант 2: Регистрация
        /// </summary>
        /// <returns></returns>
        public ActionResult Registration()
        {
            var email = Request["email"];
            if (string.IsNullOrWhiteSpace(email)) { return Redirect("/Main/IsOurUser/False"); }
            var clientID = new GLKServiceClient().CreateClient(email);
            if (clientID == 0) { return Redirect("/Main/IsOurUser/False"); }
            var cookie = FormsAuthentication.GetAuthCookie(clientID.ToString(), true);
            cookie.Expires = DateTime.Now.AddHours(2);
            Response.Cookies.Set(cookie);
            ViewBag.Action = "";
            return View("Action");
        }

        /// <summary>
        /// Шаг 3: Клиент выбирает услугу (пополнение баланса / покупка товара)
        /// </summary>
        /// <returns></returns>
        //public ActionResult Action()
        //{
            
        //}

        /// <summary>
        /// Шаг 4: Выбор услуги
        /// Вариант 1: Пополнение баланса
        /// </summary>
        /// <returns></returns>
        public ActionResult Balance()
        {
            return View();
        }

        /// <summary>
        /// Шаг 4: Выбор услуги
        /// Вариант 2: Покупка товара
        /// </summary>
        /// <returns></returns>
        public ActionResult Products()
        {
            var products = new GLKServiceClient().GetProducts();
            return View(products);
        }

        /// <summary>
        /// Шаг 5: Оплата услуги
        /// </summary>
        /// <returns></returns>
        public RedirectResult PrePay()
        {
            //todo: сделать проверку на наличие пользователя
            var userID = Convert.ToInt32(HttpContext.User.Identity.Name);
            OrderData data;
            var absoluteUrlBase = 
                Request.Url.Scheme + "://" +
                Request.Url.Host +
                (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
            var sumBalance = Request["BalanceSum"];
            if (sumBalance != null)
            {
                int balance;
                if (!int.TryParse(sumBalance, out balance)) return new RedirectResult("/Main/Balance");// RedirectToAction("Balance");
                data = new GLKServiceClient().GetPrePayDataBalance(userID, balance, absoluteUrlBase + "/Main/Return");
            }
            else
            {
                var value = 0;
                var keys = Request.Form.AllKeys.Where(x => x.Contains("item"))
                    .Select(x => x.Replace("item", ""))
                    .Where(key => int.TryParse(key, out value))
                    .Select(key => value);
                data = new GLKServiceClient().GetPrePayDataProducts(userID, keys.ToArray(), absoluteUrlBase + "/Main/Return");
            }
            
            
            //data.cb_url = absoluteUrlBase + "/Main/TransactionConfirmation";
            //data.success_url = absoluteUrlBase + "/Main/Success";
            //data.decline_url = absoluteUrlBase + "/Main/Decline";
            return new RedirectResult(data.FormUrl);// View(data);
        }

        /// <summary>
        /// Шаг 6: Завершение оплаты:
        /// </summary>
        /// <returns></returns>
        public ActionResult Return()
        {
            var bankOrderID = Request["orderId"];
            if (string.IsNullOrWhiteSpace(bankOrderID)) return null;
            var result = new GLKServiceClient().GetPaymentResult(bankOrderID);
            return View(result);
        }
        

        /// <summary>
        /// Подтверждение оплаты
        /// Действие системы электронных платежей
        /// </summary>
        /// <returns></returns>
        public EmptyResult TransactionConfirmation()
        {
            var OrderID = Request["OrderID"];
            return new EmptyResult();
        }
    }
}
